package com.bilibili.juc.atomics;

//AtomicLong和LongAdder性能测试


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
import java.util.concurrent.atomic.LongAdder;

/**
 * AtomicLong和LongAdder性能测试
 */
public class LongAdderPerf {

    public static void main(String[] args) throws InterruptedException {
        testAtomicAndLongAdder(1, 10000000);
        testAtomicAndLongAdder(10, 10000000);
        testAtomicAndLongAdder(100, 10000000);
        testAtomicAndLongAdder(1000, 10000000);

    }
    public static void testAtomicAndLongAdder(int threadCount, int times) throws InterruptedException {
        System.out.println("threadCount: " + threadCount + ", times: " + times);
        long start = System.currentTimeMillis();
        testLongAdder(threadCount, times);
        System.out.println("LongAdder 耗时："  + (System.currentTimeMillis() - start) + "ms");
        System.out.println("threadCount: " + threadCount + ", times: " + times);
        long atomicStart = System.currentTimeMillis();
        testAtomicLong(threadCount, times);
        System.out.println("AtomicLong 耗时："  + (System.currentTimeMillis() - atomicStart) + "ms");
        System.out.println("-----------------------------------------");
    }
    public static void testAtomicLong(int threadCount, int times) throws InterruptedException {
        AtomicLong a = new AtomicLong();
        List<Thread> list = new ArrayList<>();
        for(int i = 0; i < threadCount; i++){
            list.add(new Thread(() -> {
                for(int j = 0; j < times; j++){
                    a.incrementAndGet();
                }
            }));
        }
        for(Thread thread : list){
            thread.start();
        }
        for(Thread thread : list){
            thread.join();
        }
        System.out.println("AtomicLong value is : " + a.get());
    }

    public static void testLongAdder(int threadCount, int times) throws InterruptedException {
        LongAdder a = new LongAdder();
        List<Thread> list = new ArrayList<>();
        for(int i = 0; i < threadCount; i++){
            list.add(new Thread(() -> {
                for(int j = 0; j < times; j++){
                    a.increment();
                }
            }));
        }
        for(Thread thread : list){
            thread.start();
        }
        for(Thread thread : list){
            thread.join();
        }
        System.out.println("LongAdder value is : " + a.longValue());
    }
}

//原文链接：https://blog.csdn.net/qq_50313418/article/details/122442553